package com.ruyiadmin.springcloud.producer.controller.core;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ruyiadmin.springcloud.producer.common.annotations.core.AllowAnonymous;
import com.ruyiadmin.springcloud.producer.common.beans.system.JwtSettings;
import com.ruyiadmin.springcloud.producer.common.classes.system.RuYiAdminCaptcha;
import com.ruyiadmin.springcloud.producer.common.core.system.entities.ActionResult;
import com.ruyiadmin.springcloud.producer.common.components.core.RuYiRedisComponent;
import com.ruyiadmin.springcloud.producer.common.utils.system.RuYiSentinelUtil;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * <p>
 * 系统验证码服务 前端控制器
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-07-16
 */
@RestController
@RequestMapping("/RuYiAdminCaptcha")
@Api(tags = "系统验证码服务")
@EnableConfigurationProperties({JwtSettings.class})
@RequiredArgsConstructor
public class RuYiAdminCaptchaController {

    //region 服务私有属性

    private final JwtSettings jwtSettings;
    private final RuYiRedisComponent redisUtils;

    //endregion

    //region 获取系统验证码

    @GetMapping("/GetCaptcha")
    @ApiOperation(value = "获取系统验证码")
    @AllowAnonymous
    public ActionResult getCaptcha() throws BlockException, ExecutionException, InterruptedException {
        RuYiSentinelUtil.tryAcquire("QueryCaptcha");
        CompletableFuture<ActionResult> future = CompletableFuture.supplyAsync(() -> {
            ArithmeticCaptcha captcha = new ArithmeticCaptcha(200, 50, 3);
            RuYiAdminCaptcha adminCaptcha = new RuYiAdminCaptcha();
            adminCaptcha.setId(UUID.randomUUID().toString());
            // 缓存用于登录校验
            this.redisUtils.set(adminCaptcha.getId(), captcha.text(), this.jwtSettings.getSaltExpiration());
            adminCaptcha.setCaptchaPicture(captcha.toBase64());

            return ActionResult.success(adminCaptcha);
        });
        return future.get();
    }

    //endregion

}
